package cn.edu.nuc.android.oweibo.activities;

import java.util.List;

import weibo4android.Status;
import weibo4android.Weibo;
import weibo4android.WeiboException;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.ListView;
import cn.edu.nuc.android.oweibo.OWeiboApplication;
import cn.edu.nuc.android.oweibo.R;
import cn.edu.nuc.android.oweibo.adapters.StatusListAdapter;
import cn.edu.nuc.android.oweibo.layouts.LoadMoreListItem;
import cn.edu.nuc.android.oweibo.tasks.LoadMoreAsyncTask;
import cn.edu.nuc.android.oweibo.tasks.LoadMoreAsyncTask.LoadMoreStatusesResponder;
import cn.edu.nuc.android.oweibo.tasks.LoadMoreAsyncTask.LoadMoreStatusesResult;

public class StatusListActivity extends ListActivity implements LoadMoreStatusesResponder {

	final private Handler handler = new Handler();
	private OWeiboApplication app;
	private Weibo weibo;
	private StatusListAdapter adapter;
	private LoadMoreListItem headerView;
	private LoadMoreListItem footerView;
	protected ProgressDialog progressDialog;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		app = (OWeiboApplication) getApplication();
		weibo = app.getWeibo();

		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		setContentView(R.layout.main);
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (!app.isAuthorized()) {
			beginAuthorization();
		} else {
			loadTimelineIfNotLoaded();
		}
	}
	

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		return MenuHelper.openActivityFromMenuItem(this, item);
	}

	/**
	 * 产生menu项
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		return true;
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		if (v.equals(headerView)) {
			headerView.showProgress(); // 显示进度条
			loadNewerWeibos(); // 加载新微薄
		} else if (v.equals(footerView)) {
			footerView.showProgress();
			loadOlderWeibos(); // 加载旧微薄
		} else {
			// Watch out! Doesn't account for header/footer! -> Status status =
		    // adapter.getItem(position);
			Status status = (Status) getListView().getItemAtPosition(position);
			Intent intent = new Intent(this, StatusDetailActivity.class);
			intent.putExtra(StatusDetailActivity.STATUS, status);
			startActivity(intent);
		}
	}

	/**
	 * 加载旧微薄
	 */
	private void loadOlderWeibos() {
		footerView.showProgress();
		new LoadMoreAsyncTask(this, adapter.getLastId() - 1, weibo, false).execute();
	}

	/**
	 * 加载新微薄
	 */
	private void loadNewerWeibos() {
		headerView.showProgress();
		new LoadMoreAsyncTask(this, adapter.getFirstId(), weibo, true).execute();
	}

	/**
	 * 加载主时间线
	 */
	private void loadTimelineIfNotLoaded() {
		if (null == getListAdapter()) {
			progressDialog = ProgressDialog.show(
					StatusListActivity.this,
					getResources().getString(R.string.loading_title),
					getResources().getString(
							R.string.loading_home_timeline_description));
			Thread loadHomeTimelineThread = new Thread() {
				public void run() {
					loadHomeTimeline();
					handler.post(finishedLoadingListTask);
				}
			};
			loadHomeTimelineThread.start();
		}
	}
	
	/**
	 * 初始化主时间线需要的adapter
	 */
	private void loadHomeTimeline() {
		try {
			List<Status> statii = weibo.getHomeTimeline();
			adapter = new StatusListAdapter(this, statii);
		} catch (WeiboException e) {
			e.printStackTrace();
		}
	}
	
	private Runnable finishedLoadingListTask = new Runnable() {
		public void run() {
			finishedLoadingList();
		}
	};
	
	/**
	 * 初始化加载更多微薄
	 */
	private void setLoadMoreViews() {
		headerView = (LoadMoreListItem) getLayoutInflater().inflate(
				R.layout.load_more, null);
		headerView.showHeaderText();
		footerView = (LoadMoreListItem) getLayoutInflater().inflate(
				R.layout.load_more, null);
		footerView.showFooterText();
		getListView().addHeaderView(headerView);
		getListView().addFooterView(footerView);
	}

	/**
	 * 完成加载列表
	 */
	protected void finishedLoadingList() {
		setLoadMoreViews();
		setListAdapter(adapter);
		getListView().setSelection(1);
		progressDialog.dismiss();
	}

	/**
	 * 开始授权
	 */
	private void beginAuthorization() {
		String authURL = app.beginAuthorization();
		Uri uri = Uri.parse(authURL + "&display=mobile");
		Intent intent = new Intent(Intent.ACTION_VIEW, uri);
		startActivity(intent);
	}

	@Override
	public void loadingMoreStatuses() {
		setProgressBarIndeterminateVisibility(true); 
	}

	@Override
	public void statusesLoaded(LoadMoreStatusesResult result) {
		setProgressBarIndeterminateVisibility(false);
		if (result.newer) {
			adapter.appendNewer(result.statuses);
			headerView.hideProgress();
			getListView().setSelection(1);
		} else {
			adapter.appendOlder(result.statuses);
			footerView.hideProgress();
		}
	}

}